import { onMounted, onUnmounted } from 'vue'
import type { Ref } from 'vue'

export function useIntersectionObserver(target: Ref<HTMLElement | null>, callback: () => void, options = {}) {
  let observer: IntersectionObserver | null = null

  const defaultOptions = {
    rootMargin: '0px 0px 200px 0px',
  }

  onMounted(() => {
    observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            console.log('Element is in view')
            callback()
          }
        })
      },
      { ...defaultOptions, ...options }
    )

    if (target.value) {
      observer.observe(target.value)
    }
  })

  onUnmounted(() => {
    if (observer && target.value) {
      observer.unobserve(target.value)
    }
  })
}
